package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.*;
import com.sky.service.ShoppingCartService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    DishMapper dishMapper;

    @Autowired
    SetmealMapper setmealMapper;

    /**
     * 查看购物车
     * @return
     */
    @Override
    public List<ShoppingCart> getShoppingCart() {
        return shoppingCartMapper.list(BaseContext.getCurrentId());
    }

    @Override
    public void addShoppingCart(ShoppingCartDTO dto) {
        //属性copy
        ShoppingCart cart=new ShoppingCart();
        BeanUtils.copyProperties(dto,cart);
        cart.setUserId(BaseContext.getCurrentId());//设置用户id

        //查询是否有对应的套餐或者菜品订单在购物车
        ShoppingCart shoppingCart = shoppingCartMapper.selectBy(cart);
        if(shoppingCart==null){//购物车没有该菜品或者套餐

            if(cart.getDishId()!=null){//不为空说明购物车里的是菜品不是套餐
                //查询对应要添加的菜品信息
                DishVO dish = dishMapper.queryById(cart.getDishId());
                cart.setName(dish.getName());
                cart.setAmount(dish.getPrice());
                cart.setImage(dish.getImage());

            }else {//否则购物车里的是套餐
                SetmealVO setmealById = setmealMapper.queryById(cart.getSetmealId());
                cart.setName(setmealById.getName());
                cart.setAmount(setmealById.getPrice());
                cart.setImage(setmealById.getImage());

            }
            cart.setNumber(1);
            cart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(cart);

        }else{//购物车有
            shoppingCart.setNumber(shoppingCart.getNumber()+1);
            shoppingCartMapper.update(shoppingCart);
        }
    }

    @Override
    public void sub(ShoppingCartDTO dto) {
        //属性copy
        ShoppingCart cart=new ShoppingCart();
        BeanUtils.copyProperties(dto,cart);
        cart.setUserId(BaseContext.getCurrentId());//设置用户id

        //查对应的用户的购物车中对应的要减少的草品或者套餐
        ShoppingCart shoppingCart = shoppingCartMapper.selectBy(cart);
        if(shoppingCart.getNumber()>1){//判断数量，超过1数量减少1
            shoppingCart.setNumber(shoppingCart.getNumber()-1);
            shoppingCartMapper.update(shoppingCart);
            return;
        }
        //数量等于1直接删除
        shoppingCartMapper.delete(cart);
    }

    @Override
    public void clean() {
        shoppingCartMapper.clean(BaseContext.getCurrentId());
    }

    @Service
    @Slf4j
    public static class WorkspaceServiceImpl implements WorkspaceService {

        @Autowired
        private OrdersMapper orderMapper;
        @Autowired
        private UserMapper userMapper;
        @Autowired
        private DishMapper dishMapper;
        @Autowired
        private SetmealMapper setmealMapper;
        @Autowired
        private ReportMapper reportMapper;

        /**
         * 根据时间段统计营业数据
         * @param begin
         * @param end
         * @return
         */
        public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {
            /**
             * 营业额：当日已完成订单的总金额
             * 有效订单：当日已完成订单的数量
             * 订单完成率：有效订单数 / 总订单数
             * 平均客单价：营业额 / 有效订单数
             * 新增用户：当日新增用户的数量
             */

            Map map = new HashMap();
            map.put("begin",begin);
            map.put("end",end);

            //查询总订单数
            Integer totalOrderCount = reportMapper.queryOrderNumber(map);

            map.put("status", Orders.COMPLETED);
            //营业额
            BigDecimal turnover = reportMapper.queryTurnoverByLocalDateTimeAndStatus(map);
            turnover = turnover == null? BigDecimal.ZERO : turnover;

            //有效订单数
            Integer validOrderCount = reportMapper.queryOrderNumber(map);

            BigDecimal unitPrice = BigDecimal.ZERO;

            Double orderCompletionRate = 0.0;
            if(totalOrderCount != 0 && validOrderCount != 0){
                //订单完成率
                orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
                //平均客单价
                unitPrice = turnover.divide(BigDecimal.valueOf(validOrderCount),2);
            }

            //新增用户数
            Integer newUsers = reportMapper.queryUserNumber(map);

            return BusinessDataVO.builder()
                    .turnover(turnover.doubleValue())
                    .validOrderCount(validOrderCount)
                    .orderCompletionRate(orderCompletionRate)
                    .unitPrice(unitPrice.doubleValue())
                    .newUsers(newUsers)
                    .build();
        }


        /**
         * 查询订单管理数据
         *
         * @return
         */
        public OrderOverViewVO getOrderOverView() {
            Map map = new HashMap();
            map.put("begin", LocalDateTime.now().with(LocalTime.MIN));
            map.put("status", Orders.TO_BE_CONFIRMED);

            //待接单
            Integer waitingOrders = reportMapper.queryOrderNumber(map);

            //待派送
            map.put("status", Orders.CONFIRMED);
            Integer deliveredOrders = reportMapper.queryOrderNumber(map);

            //已完成
            map.put("status", Orders.COMPLETED);
            Integer completedOrders = reportMapper.queryOrderNumber(map);

            //已取消
            map.put("status", Orders.CANCELLED);
            Integer cancelledOrders = reportMapper.queryOrderNumber(map);

            //全部订单
            map.put("status", null);
            Integer allOrders = reportMapper.queryOrderNumber(map);

            return OrderOverViewVO.builder()
                    .waitingOrders(waitingOrders)
                    .deliveredOrders(deliveredOrders)
                    .completedOrders(completedOrders)
                    .cancelledOrders(cancelledOrders)
                    .allOrders(allOrders)
                    .build();
        }

        /**
         * 查询菜品总览
         *
         * @return
         */
        public DishOverViewVO getDishOverView() {
            Map map = new HashMap();
            map.put("status", StatusConstant.ENABLE);
            Integer sold = dishMapper.countByMap(map);

            map.put("status", StatusConstant.DISABLE);
            Integer discontinued = dishMapper.countByMap(map);

            return DishOverViewVO.builder()
                    .sold(sold)
                    .discontinued(discontinued)
                    .build();
        }

        /**
         * 查询套餐总览
         *
         * @return
         */
        public SetmealOverViewVO getSetmealOverView() {
            Map map = new HashMap();
            map.put("status", StatusConstant.ENABLE);
            Integer sold = setmealMapper.countByMap(map);

            map.put("status", StatusConstant.DISABLE);
            Integer discontinued = setmealMapper.countByMap(map);

            return SetmealOverViewVO.builder()
                    .sold(sold)
                    .discontinued(discontinued)
                    .build();
        }
    }
}
